package me.zhengjie.utils;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class AliMessageUtil {

    private static final Logger log = LoggerFactory.getLogger(AliMessageUtil.class);
    /**
     * 发放验证码
     * @param mobile
     * @return
     */
    public boolean verifyCode(String mobile,String code){
        try {
            if (StringUtils.isAnyBlank(mobile,code)){
                return false;
            }
            Client client = createClient("LTAI5tPjcHxyQSu9F633L5CE", "Uk8Gk7vVmKqh32rKpbxxiCl5ausy1L");
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            sendSmsRequest.setPhoneNumbers(mobile);
            sendSmsRequest.setSignName("南京德容智慧");
            sendSmsRequest.setTemplateCode("SMS_227660233");
            Map<String,Object> paramMap = new HashMap<>();
            //NumberUtil.generateRandomNumber(1000,99999999,4)
            //RandomUtil.randomNumbers( 4)
            paramMap.put("code", code);
            sendSmsRequest.setTemplateParam(JSON.toJSONString(paramMap));
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            log.info(JSON.toJSONString(sendSmsResponse));
            if (null != sendSmsResponse && sendSmsResponse.getBody() != null && sendSmsResponse.getBody().getCode().equalsIgnoreCase("OK")){
                return true;
            }
        } catch (Exception e) {
        }
        return false;
    }

    public static void main(String[] args) {
        AliMessageUtil util = new AliMessageUtil();
        boolean b = util.verifyCode("13770654123", "1111");
    }
    private Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }
}
